package com.zhijian.medical.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.SangerHszbqMapper;
import com.zhijian.medical.entity.po.ExperimentProcessSample;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerHszbq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerHszbqSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerHszbqSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleNgsOrSangerVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerHszbqVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.SangerHszbqService;
import com.zhijian.medical.service.SangerService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 一代测序-核酸制备区 业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-11 17:14:35
 */
@Slf4j
@Service
public class SangerHszbqServiceImpl implements SangerHszbqService {

    @Autowired
    private SangerHszbqMapper mapper;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerHszbq selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerHszbq selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerHszbqVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerHszbqVo selectVoBySangerId(Long sangerId) {
        SangerHszbqVo sangerHszbqVo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerHszbqVo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerHszbqVo.setResult(sanger.getStatus() > SangerStatusEnum.HSZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerHszbqVo.setResultStr(sanger.getStatus() > SangerStatusEnum.HSZBQ.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        //准备数据
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .experimentProcessId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(experimentProcessSampleVos)) {
            sangerHszbqVo.setSangerReadyList(experimentProcessSampleVos.stream().map(e -> {
                ExperimentProcessSampleNgsOrSangerVo experimentProcessSampleNgsOrSangerVo = new ExperimentProcessSampleNgsOrSangerVo();
                BeanUtils.copyProperties(e, experimentProcessSampleNgsOrSangerVo);
                return experimentProcessSampleNgsOrSangerVo;
            }).collect(Collectors.toList()));
        }
        return sangerHszbqVo;
    }

    @Override
    public boolean saveOrUpdate(SangerHszbq sangerHszbq) {
        SangerHszbq oldSangerHszbq = this.selectBySangerId(sangerHszbq.getSangerId());
        if (Objects.isNull(oldSangerHszbq)) {
            this.insert(sangerHszbq);
        } else {
            sangerHszbq.setId(oldSangerHszbq.getId());
            this.update(sangerHszbq);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerHszbqSaveOrUpdateVo sangerHszbqSaveOrUpdateVo) {
        Long sangerId = sangerHszbqSaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        if (sanger.getStatus() < SangerStatusEnum.HSKZYQ.getCode().byteValue()) {
            //将实验的状态修改
            sangerService.updateByPrimaryKeySelective(Sanger.builder()
                    .id(sangerId)
                    .status(SangerStatusEnum.HSKZYQ.getCode().byteValue())
                    .build());
        }
        SangerHszbq oldSangerHszbq = this.selectBySangerId(sangerId);
        SangerHszbq dbParam = new SangerHszbq();
        BeanUtils.copyProperties(sangerHszbqSaveOrUpdateVo, dbParam);
        if (Objects.isNull(oldSangerHszbq)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldSangerHszbq.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleUpdateVo> sangerReadyList = sangerHszbqSaveOrUpdateVo.getSangerReadyList();
        if (CollectionUtil.isEmpty(sangerReadyList)) {
            return false;
        }
        sangerReadyList.forEach(e -> {
            ExperimentProcessSample updateParam = new ExperimentProcessSample();
            BeanUtil.copyProperties(e, updateParam, "moleculePathologyNumber", "project");
            experimentProcessSampleService.updateByPrimaryKeySelective(updateParam);
        });
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.HSZBQ.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerHszbq sangerHszbq) {
        Date now = new Date();
        sangerHszbq.setCreateTime(now);
        sangerHszbq.setUpdateTime(now);
        if (Objects.isNull(sangerHszbq.getSystmqj())) {
            sangerHszbq.setSystmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getZlxbblsffh())) {
            sangerHszbq.setZlxbblsffh(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getCddnandycd())) {
            sangerHszbq.setCddnandycd(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getTzdnand())) {
            sangerHszbq.setTzdnand(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getJtzhddnajrdydfygn())) {
            sangerHszbq.setJtzhddnajrdydfygn(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getGsgg())) {
            sangerHszbq.setGsgg(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getGcywyc())) {
            sangerHszbq.setGcywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getLxj())) {
            sangerHszbq.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getZdq())) {
            sangerHszbq.setZdq(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getAqgt())) {
            sangerHszbq.setAqgt(StatusEnum.NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getQjjzwxzssygztm())) {
            sangerHszbq.setQjjzwxzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getQjyyq())) {
            sangerHszbq.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getQjlxj())) {
            sangerHszbq.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        if (Objects.isNull(sangerHszbq.getClsyfqw())) {
            sangerHszbq.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        }
        return mapper.insert(sangerHszbq) > 0 ? sangerHszbq.getId() : 0L;
    }

    @Override
    public boolean update(SangerHszbq sangerHszbq) {
        Date now = new Date();
        sangerHszbq.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerHszbq) != 0;
    }

    @Override
    public Integer count(SangerHszbqSearchVo sangerHszbqSearchVo) {
        return mapper.count(sangerHszbqSearchVo);
    }

    @Override
    public List<SangerHszbqVo> selectList(SangerHszbqSearchVo sangerHszbqSearchVo) {
        return mapper.selectList(sangerHszbqSearchVo);
    }

    @Override
    public Page<SangerHszbqVo> selectPage(SangerHszbqSearchVo sangerHszbqSearchVo) {
        //先直接查总数
        int count = count(sangerHszbqSearchVo);
        //分页
        Page<SangerHszbqVo> page = new Page<>(true, count, sangerHszbqSearchVo.getPageNum(), sangerHszbqSearchVo.getPageSize());
        sangerHszbqSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerHszbqVo> responseVos = this.selectList(sangerHszbqSearchVo);
        page.setData(responseVos);
        return page;
    }

}